<template>
  <div class='echart' ref='echart'>
    <div class='echarts' ref='echarts' res='chart' />
    <div class="show-info">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  props: {
    echartData: {
      type: Array,
      default () {
        return []
      }
    },
    color: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      myChart: null
    }
  },
  methods: {
    initChart () {
      const chartDom = this.$refs.echarts
      this.myChart = echarts.init(chartDom)
      // 判断数据是否全部为0 测试提出 为0不展示
      let AllZero = this.echartData.find((item) => item.value !== 0)
      let data = this.echartData
      // 全部为0 需要展示
      if (AllZero) {
        data = data.map((item) => {
          return {
            ...item,
            // 因为规定了最小角度 所以将0的数据改为-1 达到不展示的效果
            value: item.value === 0 ? -1 : item.value
          }
        })
      }
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c} ({d}%)'
        },
        series: [
          {
            // name: 'Access From',
            center: ['50%', '50%'],
            type: 'pie',
            radius: '90%',
            minAngle: 5, // 最小角度
            startAngle: 130, // 起始角度
            label: {
              normal: {
                formatter: '{b}:{c}\n({d}%)',
                position: 'inside',
                textStyle: {
                  fontWeight: 'normal',
                  fontSize: 12
                }
              }
            },
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      if (this.color && this.color.length > 0) {
        option.color = this.color
      }
      if (option && chartDom && this.echartData.length !== 0) {
        this.myChart.setOption(option)
        this.myChart.resize()
      } else {
        chartDom.innerHTML = ''
        chartDom.removeAttribute('_echarts_instance_')
      }
    }
  },
  mounted () {
    this.initChart()
    window.addEventListener('resize', () => {
      this.myChart.resize()
    })
  },
  watch: {
    echartData: {
      deep: true,
      handler () {
        this.initChart()
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.echart {
  height: 100%;
  display: flex;
}
.echarts {
  color: #0e521a;
  width: 70%;
  height: 100%;
}
.show-info {
  margin-top: 30px;
}
</style>
